package com.fanshuai2.test;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class StringReplace {
    static String stringReplace(String s, Map<String, Object> map) {
        if (null == s || s.length() == 0)  {
            return s;
        }

        char[] arr = s.toCharArray();
        int p0 = 0, p1 = 0;
        Map<String, String> replaceMap = new LinkedHashMap<>();

        for (int i = 0; i < arr.length; i++) {
            char c = arr[i];

            if (c == '{') {
                if (i < arr.length - 1 && arr[i + 1] == '{') {
                    p0 = i;
                }
            } else if (c == '}') {
                if (i < arr.length - 1 && arr[i + 1] == '}') {
                    p1 = i + 1;

                    String placeHolder = s.substring(p0, p1 + 1);
                    String key = placeHolder.substring(2, placeHolder.length() - 2);
                    key = key.trim();
                    Object o = map.get(key);
                    if (null == o) {
                        throw new RuntimeException("the variable \"{key}\" is missing from the keys of the values object".replace("{key}", key));
                    }

                    replaceMap.put(placeHolder, String.valueOf(o));
                }
            }
        }
        for (String replace: replaceMap.keySet()) {
            s = s.replace(replace, replaceMap.get(replace));
        }

        return s;
    }

    public static void main(String[] args) {
        String s = "My name is {{ name }} and I am forever {{ age }}.";
        Map<String, Object> map = new HashMap<>();
        map.put("name", "fanshuai");
        map.put("age", 18);
        System.out.println(stringReplace(s, map));


        s = "Say hello to {{ name }}. He is {{ age }}.";
        map = new HashMap<>();
        map.put("name", "Bill");
        map.put("age", 21);
        map.put("male", true);
        System.out.println(stringReplace(s, map));

//        s = "Tommy is a good friend of {{ name }}. He lives in {{ city }}.";
//        map = new HashMap<>();
//        map.put("name", "Bill");
//        System.out.println(stringReplace(s, map));
    }
}
